/*
 * SPI.c
 *
 * Created: 27.02.2013 12:39:57
 *  Author: saenko
 */ 

#include "avr/io.h"

#define cbi(reg,bit)	reg &= ~(_BV(bit))
#define sbi(reg,bit)	reg |= (_BV(bit))

#define SPI_DDR DDRB
#define SPI_PORT PORTB
#define SPI_PIN PINB

#define SPI_SS PB2
#define SPI_SCK PB5
#define SPI_MOSI PB3
#define SPI_MISO PB4

#define SPI_SS_UP sbi(SPI_PORT,SPI_SS)
#define SPI_SS_DOWN cbi(SPI_PORT,SPI_SS)

void spi_init(void)
{
	SPCR = (1<<SPE)|(1<<MSTR)|(1<<CPHA)|(SPR0);
	SPI_DDR = (1<<SPI_SS)|(1<<SPI_SCK)|(1<<SPI_MOSI)|(0<<SPI_MISO);
	SPI_SS_UP;
}

uint16_t spi_write(uint16_t data)
{
	uint16_t data_in;
	
	uint8_t temp;
	
	temp = data;
	
	data = data >> 8;
	
	SPI_SS_DOWN;
		
	SPDR = data;
	
	while(!(SPSR & (1<<SPIF)));
	
	data_in = SPDR;
	
	data_in = data_in << 8;
		
	SPDR = temp;
	
	while(!(SPSR & (1<<SPIF)));
	
	data_in = data_in + SPDR;
	
	SPI_SS_UP;
}